<template>
  <div class="app-container">
    <el-form ref="queryFormRef" :model="page.queryForm" inline>
      <el-form-item label="部门名称" prop="dept_name">
        <el-input
          v-model="page.queryForm.dept_name"
          @keyup.enter="getDeptList"
          clearable
          placeholder="请输入部门名称"
        ></el-input>
      </el-form-item>
      <el-form-item label="状态" prop="status">
        <el-input
          v-model="page.queryForm.status"
          placeholder="请输入部门名称"
        ></el-input>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="Search" @click="getDeptList">搜索</el-button>
        <el-button icon="Refresh" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <vxe-toolbar
      ref="toolbarRef"
      custom
      print
      :refresh="{ query: getDeptList }"
    >
      <template #buttons>
        <el-button type="primary" icon="Plus" plain @click="handleAdd()">新增</el-button>
        <el-button type="info" icon="Sort" plain @click="handleExpand">展开/折叠</el-button>
      </template>
    </vxe-toolbar>

    <vxe-table
      ref="deptTableRef"
      border="inner"
      align="center"
      :column-config="{ resizable: true }"
      :row-config="{ isHover: true }"
      :print-config="{}"
      :tree-config="{
        transform: true,
        rowField: 'dept_id',
        parentField: 'parent_id',
        iconOpen: 'vxe-icon-square-minus',
        iconClose: 'vxe-icon-square-plus',
      }"
      :loading="loading"
      :data="tableData"
    >
      <vxe-column field="dept_name" title="部门名称" tree-node></vxe-column>
      <vxe-column field="order_num" title="排序" width="60"></vxe-column>
      <vxe-column title="状态">
        <template #default="{ row }">
          <el-tag :type="row.status === '0' ? '' : 'danger'">
            {{ row.status === "0" ? "正常" : "停用" }}
          </el-tag>
        </template>
      </vxe-column>
      <vxe-column field="create_time" title="创建时间"></vxe-column>
      <vxe-column title="操作">
        <template #default="{ row }">
          <el-button link type="primary" icon="Edit" @click="handleUpdate(row)"
            >修改</el-button
          >
          <el-button link type="primary" icon="Plus" @click="handleAdd(row)"
            >新增</el-button
          >
          <el-popconfirm
            title="您确定要删除此数据吗?"
            confirm-button-text="确认"
            cancel-button-text="取消"
            @confirm="handleDelete(row)"
          >
            <template #reference>
              <el-button link type="primary" icon="Delete">删除</el-button>
            </template>
          </el-popconfirm>
        </template>
      </vxe-column>
    </vxe-table>

    <el-dialog
      v-model="open"
      :title="title"
      width="700px"
      append-to-body
      @closed="reset"
    >
      <el-form
        ref="formRef"
        :model="page.form"
        :rules="page.rules"
        label-width="120px"
      >
        <el-form-item label="上级部门" prop="parent_id">
          <el-tree-select
            v-model="page.form.parent_id"
            :props="{
              value: 'dept_id',
              label: 'dept_name',
              children: 'children',
            }"
            :default-expanded-keys="['0']"
            value-key="dept_id"
            :data="deptOptions"
            check-strictly
            placeholder="请选择上级部门"
          />
        </el-form-item>
        <el-row>
          <el-col :span="12">
            <el-form-item label="部门名称" prop="dept_name">
              <el-input
                v-model="page.form.dept_name"
                placeholder="请输入部门名称"
              />
            </el-form-item>
          </el-col>

          <el-col :span="12">
            <el-form-item label="显示排序" prop="order_num">
              <el-input-number
                v-model="page.form.order_num"
                :min="0"
                :max="99"
              />
            </el-form-item>
          </el-col>

          <el-col :span="12">
            <el-form-item label="负责人" prop="leader">
              <el-input
                v-model="page.form.leader"
                placeholder="请输入负责人名称"
              />
            </el-form-item>
          </el-col>

          <el-col :span="12">
            <el-form-item label="联系电话" prop="phone">
              <el-input
                v-model="page.form.phone"
                placeholder="请输入联系电话"
              />
            </el-form-item>
          </el-col>

          <el-col :span="12">
            <el-form-item label="邮箱" prop="email">
              <el-input v-model="page.form.email" placeholder="请输入邮箱" />
            </el-form-item>
          </el-col>

          <el-col :span="12">
            <el-form-item label="部门状态" prop="status">
              <el-radio-group v-model="page.form.status">
                <el-radio label="0">正常</el-radio>
                <el-radio label="1">停用</el-radio>
              </el-radio-group>
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="open = false">取消</el-button>
          <el-button type="primary" @click="submit"> 确认 </el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted, nextTick } from "vue";
import {
  deptList,
  deptAdd,
  deptEdit,
  deptDel,
  deptInfo,
} from "@/api/system/dept.ts";

const queryFormRef = ref();
const deptTableRef = ref();
const toolbarRef = ref();
const formRef = ref();

const page = reactive({
  // query表单
  queryForm: {
    dept_name: null,
    status: null,
  },
  // 新增、修改表单数据
  form: {
    dept_id: null,
    parent_id: "0",
    dept_name: null,
    order_num: null,
    leader: null,
    phone: null,
    status: "0",
  },
  rules: {
    dept_name: [
      { required: true, message: "部门名称不能为空", trigger: "blur" },
    ],
    order_num: [
      { required: true, message: "部门顺序不能为空", trigger: "blur" },
    ],
    path: [{ required: true, message: "路由地址不能为空", trigger: "blur" }],
  },
});

// 表格数据
const tableData = ref([]);
// 部门树选项
const deptOptions = ref([]);
// 加载状态
const loading = ref(false);
// 树表格是否展开
const isExpand = ref(false);
// 新增、修改对话框的显示与隐藏getDeptList
const open = ref(false);
// 对话框标题
const title = ref("");

nextTick(() => {
  // 将表格和工具栏进行关联
  const $table = deptTableRef.value;
  const $toolbar = toolbarRef.value;
  if ($table && $toolbar) {
    $table.connect($toolbar);
  }
});

onMounted(() => {
  getDeptList();
});

/**
 * 重置查询
 */
function resetQuery() {
  queryFormRef.value.resetFields();
  getDeptList();
}

/**
 * 树表格展开/折叠事件
 */
function handleExpand() {
  isExpand.value = !isExpand.value;
  if (isExpand.value) {
    deptTableRef.value.setAllTreeExpand(true);
  } else {
    deptTableRef.value.clearTreeExpand();
  }
}

/**
 * 新增部门
 */
function handleAdd(row = null) {
  if (row) {
    page.form.parent_id = row.dept_id;
    page.form.dept_type = row.dept_type;
  }
  getdeptTree();
  open.value = true;
  title.value = "新增部门";
}

/**
 * 修改部门
 * @param {Object} row 行数据
 */
function handleUpdate(row) {
  deptInfo(row.dept_id).then((res) => {
    page.form = res.data;
    getdeptTree();
    open.value = true;
    title.value = "修改部门";
  });
}

/**
 * 删除部门
 * @param {Object} row 行数据
 */
function handleDelete(row) {
  deptDel(row.dept_id).then((res) => {
    getDeptList();
  });
}

/**
 * 获取部门列表
 */
function getDeptList() {
  loading.value = true;
  deptList(page.queryForm)
    .then((res) => {
      tableData.value = res.data;
    })
    .finally(() => {
      loading.value = false;
    });
}

/**
 * 获取部门树
 */
function getdeptTree() {
  deptList()
    .then((res) => {
      deptOptions.value = [
        {
          dept_id: "0",
          dept_name: "总公司",
          children: listToTree(res.data, "0"),
        },
      ];
    })
    .finally(() => {
      loading.value = false;
    });
}

/**
 * 列表转树
 * @param {Array} list 列表
 * @param {String} parentId 父级id
 */
function listToTree(list, parentId) {
  return list
    .filter((item) => item.parent_id === parentId)
    .map((item) => ({
      ...item,
      children: listToTree(list, item.dept_id),
    }));
}

/**
 * 部门类型改变
 * @param {*} e
 */
function deptTypeChange(e) {
  page.form.dept_type = e;
}

/**
 * 提交
 */
function submit() {
  formRef.value.validate((valid) => {
    if (valid) {
      if (page.form.dept_id) {
        deptEdit(page.form.dept_id, page.form).then((res) => {
          open.value = false;
          getDeptList();
        });
      } else {
        deptAdd(page.form).then((res) => {
          open.value = false;
          getDeptList();
        });
      }
    }
  });
}

/**
 * 重置
 */
function reset() {
  formRef.value.resetFields();
}
</script>

<style lang="scss" scoped></style>
